#include "comm.hpp"
extern Log log;
#include <unistd.h>

int main() 
{
    Init init;   //创建管道用来控制SH_Mem
    int shmid = CreateShm();
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);       //void *shmat(int shmid, const void *shmaddr, int shmflg);
    // 一旦有人把数据写入到共享内存，其实我们立马能看到了！！
    // 不需要经过系统调用，直接就能看到数据了！
    
    int fd = open(FIFO_FILE, O_RDONLY);         // 等待写入方打开之后，自己才会打开文件，向后执行， open 阻塞了！
    if (fd < 0)
    {
        log(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
        exit(FIFO_OPEN_ERR);
    }

    struct shmid_ds shmds;      //shmctl的输出型参数，用来获取shm信息

    while (true)
    {
        char signal;
        ssize_t n = read(fd, &signal, sizeof(signal));      //用来进行同步控制
        if (n < 0)
        {
            log(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
            break;
        }   
        if (n == 0)
        {
            log(Info, "fifo closed");
            break;
        }

        //n > 0
        cout << "process b received msg: " << shmaddr << endl;  //直接访问共享内存
        sleep(1);

        // 打印共享内存信息
        shmctl(shmid, IPC_STAT, &shmds);
        cout << "shm size: " << shmds.shm_segsz << endl;
        cout << "shm nattch: " << shmds.shm_nattch << endl;
        printf("shm key: 0x%x\n",  shmds.shm_perm.__key);
        cout << "shm mode: " << shmds.shm_perm.mode << endl;
    }


    shmdt(shmaddr);         //取消挂接
    shmctl(shmid, IPC_RMID, nullptr);      //删除共享内存

    close(fd);  

    return 0;
}